package com.kgc.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.api.goods.OrderApi;
import com.kgc.bean.OrderInfo;
import com.kgc.bean.OrderItem;
import com.kgc.bean.User;
import com.kgc.config.annotation.RequestPermission;
import com.kgc.config.annotation.RequestUser;
import com.kgc.constant.WxpayConstant;
import com.kgc.service.UserService;
import com.kgc.service.WeChatPayService;
import com.kgc.util.RedisUtils;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Classname MemberController
 * @Description 会员控制层
 * @Date 2021/6/23 16:01
 * @Created by 17402
 */
@Slf4j
@Api(tags = "购买会员")
@RestController
public class MemberController extends BaseController{

    @Autowired
    private WeChatPayService weChatPayService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;
    @Reference(timeout = 30000)
    private OrderApi orderApi;

    @RequestPermission
    @PostMapping("/buyVip")
    @ApiOperation(value = "购买会员",notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "month", value = "月数", required = true)})
    public ReturnResult<Map<String,String>> BuyMember(@ApiIgnore @RequestUser User user, HttpServletRequest request,  @RequestParam Integer month) throws Exception {

        //获取微信统一下单字符串
        if(null==user||user.getUserId()==null){
            ResultBuildUtil.fail("1001","用户token无效");
        }
        redisUtils.set("month",month);
        String wxorderParams2XmlStr = weChatPayService.createWxorderParam2XmlStr(String.valueOf(month*1), "购买会员", this.getRemoteIp(request),request.getHeader("token"));
        log.info("------1 获取微信统一下单接口：{}",wxorderParams2XmlStr);

        //调用微信接口统一返回
        Map<String, String> stringStringMap = weChatPayService.send2WechatPayOrder(wxorderParams2XmlStr);
        log.info("------2 发送微信统一下单返回：{}", stringStringMap);

        //统一返回处理
        Map<String, String> weChatPayReturnData = new HashMap<>();

        //在return_code 和result_code都为SUCCESS的时候有返回支付url
        if (WxpayConstant.WXPAY_RETURN_SUCCESS.equals(stringStringMap.get(WxpayConstant.WXPAY_RETURN_CODE) )
                &&
                WxpayConstant.WXPAY_RETURN_SUCCESS.equals(stringStringMap.get(WxpayConstant.WXPAY_RESULT_CODE))
        ) {
            weChatPayReturnData.put(WxpayConstant.WXPAY_TRADE_TYPE, stringStringMap.get(WxpayConstant.WXPAY_TRADE_TYPE));
            weChatPayReturnData.put(WxpayConstant.WXPAY_PREPAY_ID, stringStringMap.get(WxpayConstant.WXPAY_PREPAY_ID));
            weChatPayReturnData.put(WxpayConstant.WXPAY_CODE_URL, stringStringMap.get(WxpayConstant.WXPAY_CODE_URL));
            return ResultBuildUtil.success(weChatPayReturnData);
        }
        return ResultBuildUtil.fail();
    }

    /**
     * @description:微信支付接口回调接口
     * @param:
     * @return:
     * @author yintao
     * @date 2021/6/23 17:45
     */
    @ApiIgnore
    @RequestMapping(value = "/wxNotify",method ={ RequestMethod.POST,RequestMethod.GET})
    public void wxPayNotify(@RequestUser User user, HttpServletRequest request, HttpServletResponse response)throws Exception{
        // 接受微信官方的异步通知
        StringBuffer wechatNotifyXmlStr = new StringBuffer();
        String return2WxPay = "";
        // 返回结果以数据流方式返回
        try (InputStream inputStream = request.getInputStream()) {
            // 高效读
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String readLine = "";
            while ((readLine = bufferedReader.readLine() )!= null) {
                wechatNotifyXmlStr.append(readLine);
            }
            log.info("微信回调的request：{}",request);
            log.info("微信回调的信息：{}",wechatNotifyXmlStr);
            //生成订单编号
            String tradeOrderNo = "T" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()) + UUID.randomUUID().toString().replace("-", "").substring(0, 6);
            Random random = new Random();
            String memberOrderNo = "V" + random.nextInt(10000);;
            OrderItem orderItem=new OrderItem();
            int month=(Integer) redisUtils.get("month");
            orderItem.setOrderId(tradeOrderNo);
            orderItem.setGoodsId(memberOrderNo);
            orderItem.setNum(1);
            orderItem.setTitle("会员购买");
            orderItem.setPrePrice(month);
            orderItem.setTotalPrice(month);
            orderApi.saveOrderItem(orderItem);
            log.info("--------------订单编号：{}",tradeOrderNo);
            return2WxPay= weChatPayService.resolveWechatPayNotify(wechatNotifyXmlStr.toString(),orderItem);
            log.info("------5返回给微信端的信息:{}",return2WxPay);


        } catch (IOException e) {
            e.printStackTrace();
        }
        // 同步响应信息
        PrintWriter out = response.getWriter();
        out.write(return2WxPay);
        out.flush();
        out.close();

    }


}
